package logic

import (
	"context"
	"errors"
	"fmt"
	"go-pod/rpc/common/jwtutil"
	"go-pod/rpc/model"

	"go-pod/rpc/internal/svc"
	"go-pod/rpc/rpc/user"

	"github.com/zeromicro/go-zero/core/logx"
	"golang.org/x/crypto/bcrypt"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Login 登录
func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	u, err := l.svcCtx.UsersModel.FindOneByUsername(l.ctx, in.Username)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			fmt.Println("find user by username err: ", err)
			return nil, errors.New("用户不存在")
		}
		return nil, err
	}
	//判断密码是否一样
	if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(in.Password)); err != nil {
		return nil, errors.New("密码错误")
	}

	// 3. 使用工具包生成令牌对
	accessToken, refreshToken, err := jwtutil.GenerateTokenPair(
		l.svcCtx.Config.Jwt.AccessSecret,
		l.svcCtx.Config.Jwt.AccessExpire,
		l.svcCtx.Config.Jwt.AccessExpire*2, // 刷新令牌过期时间为访问令牌的两倍
		u.Id,
	)

	if err != nil {
		return nil, errors.New("生成token错误")
	}

	return &user.LoginResponse{
		UserId:       u.Id,
		Token:        accessToken,
		RefreshToken: refreshToken,
	}, nil
}
